<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      :searchNum="searchItemCount"
      v-model:form-value="state.query"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      @submit="searchFn"
    >
      <el-col :span="8" class="flex-center">
        <FIFormItem name="resourceEname" label="资源编码">
          <FIInput v-model="state.query.resourceEname" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="8" class="flex-center">
        <FIFormItem name="resourceCname" label="资源名称">
          <FIInput v-model="state.query.resourceCname" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="8" class="flex-center">
        <FIFormItem prop="type" label="资源类型">
          <FISelect v-model="state.query.type" valueCustom="value" :options="dataArr" clearable />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="资源信息管理列表"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="state.dataList"
      primaryKey="resourceId"
      insertable
      deletable
      v-model:columns="columns"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="actionClick"
      @row-delete="deleteRow"
    >
      <!-- <template #headerBtn>
        <FIPopconfirmBtn
          title="您是否确认删除选中数据吗？"
          buttonText="删除"
          beforePopText="请选择一条数据"
          :btn-binds="{ id: 'delete', border: true }"
          @confirm="deleteRow"
        >
        </FIPopconfirmBtn>
      </template> -->
      <template #type="{ scope }">
        <FISelect
          v-if="scope.row.isSelected"
          v-model="scope.row.type"
          valueCustom="value"
          :options="dataArr"
          clearable
        />
        <span v-else>{{ typeFucn(scope.row.type, scope.$index) }}</span>
      </template>
    </FITable>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'

import { apiRequestPost } from '@/api/globalApi.js'
import LocalCache from '@/utils/cache'
import { ElMessage } from 'element-plus'
import { useMessage, useMessageBox } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import {
  apiResourceMaintQuery,
  apipageFavorDelete,
  apiResourceMaintSave,
  apiGetCodeitems,
} from '@/api/configEnvMaint/index.ts'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
const route = useRoute()

const searchWrapperSpan = 8
const showSearch = ref(true)
const isTableLoading = ref(false)
// 页面编码
const tableId = 'resourceMaint'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)

const state = reactive({
  query: {
    resourceEname: '',
    resourceCname: '',
    type: '',
    current: 1,
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const dataArr = ref([])
const columns: Column[] = reactive([
  {
    label: '资源编码',
    prop: 'resourceEname',
    align: 'center',
    editType: 'input',
    editable: true,
    sortable: false,
    readonly: true,

    modelValue: {
      inputValue: '',
      isBlank: false,
      notBlank: false,
    },
    editConfig: {
      rules: { resourceEname: [{ required: true, message: '请输入资源编码', trigger: 'blur' }] },
    },
  },
  {
    label: '资源名称',
    prop: 'resourceCname',
    align: 'center',
    editable: true,
    modelValue: { inputValue: '' },
    editType: 'input',
    editConfig: {
      rules: { resourceCname: [{ required: true, message: '请输入资源名称', trigger: 'blur' }] },
    },
  },
  {
    label: '类型',
    prop: 'type',
    align: 'center',
    editable: true,
    editType: 'select',
    modelValue: { inputValue: '' },
    editConfig: {
      rules: { type: [{ required: true, message: '请选择类型', trigger: 'change' }] },
      options: dataArr,
    },
  },
  {
    label: '是否授权',
    prop: 'isAuth',
    align: 'center',
    editable: true,
    filterable: false,
    sortable: false,
    modelValue: { inputValue: '' },
    editType: 'select',
    sortValue: '',
    editConfig: {
      rules: { isAuth: [{ required: true, message: '请选择是否授权', trigger: 'change' }] },
      options: [
        { value: '1', label: '是' },
        { value: '0', label: '否' },
      ],
    },
    selectBinds: {
      multiple: false,
      valueCustom: 'value',
    },
  },
  {
    label: '创建人',
    prop: 'recCreator',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '创建时间',
    prop: 'recCreateTime',
    align: 'center',
    editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改人',
    prop: 'recRevisor',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改时间',
    prop: 'recReviseTime',
    align: 'center',
    editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const typeFucn = (id, index) => {
  for (let i of dataArr.value) {
    if (i.value == id) {
      return i.label
    }
  }
  // arr2.value.forEach((item: any) =>{
  //   if(item.value == id){
  //     console.log(item.label,'item.label')
  //     return item.label
  //   }
  // })
}
const smallCode = () => {
  apiGetCodeitems({ codesetCode: 'services.xs.resourcesTypes' })
    .then((res) => {
      console.log(res, '小代码')
      if (res.data.success) {
        dataArr.value = res.data.data.map((v) => {
          return {
            label: v.itemCname,
            value: v.itemCode,
          }
        })
        tableRef.value.cloneColumnList.forEach((v) => {
          if (v.prop == 'subsecType') {
            v.editConfig.options = dataArr
          }
        })
      }
    })
    .catch((error: any) => {})
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}

//删除事件
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.resourceId) ids.push(item?.resourceId)
    })
  isTableLoading.value = true
  const apiUrl = proxy.$Button_api('delete', route.name)
  apiRequestPost(apiUrl, ids)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(res.data.message)
        searchFn()
      }
    })
    .catch((error: any) => {
      useMessage().error(error.data.message)
      isTableLoading.value = false
    })
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
// 隐藏搜索项有值的个数
const searchItemCount = computed(() => {
  let filledCount = 0
  const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
  // 下面是从第三项起计算常规搜索条件有值个树
  // 获取state.query的所有keys
  const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
  if (queryKeys.length < 3) return 0
  // 从第三项开始计算
  queryKeys.slice(2).forEach((key) => {
    if (state.query[key] !== '' && state.query[key] !== null) {
      filledCount++
    }
  })
  return filledCount
})
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const apiUrl = proxy.$Button_api('query', route.name)
  apiRequestPost(apiUrl, state.query)
    .then((res) => {
      isTableLoading.value = false
      console.log(res, 'res123')
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  apiResourceMaintSave(checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
//   const exportRow = () => {
//     apiGroupUserExport(state.query)
//   }
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave()
}
onMounted(() => {
  smallCode()
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  searchFn()
})
</script>
<style lang="less" scoped></style>
